/*
 * Copyright 2006-2007 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package asphalt2.util
{
	import flash.display.DisplayObject;
	import flash.events.EventDispatcher;
	import mx.core.Container;
	import mx.core.Application;
	
	/**
	 * @author c9katayama
	 */
	public class UIUtil
	{
		public function UIUtil()
		{
			throw new Error("prohibited instantiation.");
		}	
		/**
		 * targetが自分か自分の親オブジェクトかどうかをチェックします。
		 **/	
		public static function isParentOrThis(comp:DisplayObject,target:DisplayObject):Boolean{
			if(comp==target)
				return true;
			return isParent(comp,target);
		}
		/**
		 * targetが自分の親オブジェクトかどうかをチェックします。
		 **/	
		public static function isParent(comp:DisplayObject,target:DisplayObject):Boolean{
			if(!(target is Container)){
				return false;
			}
			var _parent:DisplayObject = comp.parent;
			while(true){
				if(_parent == null){
					break;
				}else{
					if(_parent == target){
						return true;
					}
				}
				_parent = _parent.parent;
			}
			return false;
		}
		/**
		 * 引数のコンポーネントの一番上の親を返します。
		 * 引数がnullの場合、Application.applicationから検索を行います。 
		 **/
		public static function findRoot(comp:DisplayObject=null):DisplayObject
		{
			if(comp==null){
				comp = Application.application as DisplayObject;
			}
			var root:DisplayObject = comp;
			while(true){
				var parent:DisplayObject = root.parent;
				if(parent==null){
					return root;					
				}else{
					root = parent;
				}
			}
			return Application.application.stage;
		}
		/**
		 * 1回のみ実行するイベントリスナーを追加します。 
		 **/
		public static function addOnceEventListener(dispatcher:EventDispatcher,eventType:String,listener:Function):void{
			var f = function(e):void{
				dispatcher.removeEventListener(eventType,f);
				listener(e);
			};
			dispatcher.addEventListener(eventType,f);
		}
	}
}